<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use DB;
use Illuminate\Http\Request;
use Session;

class ShopCarController extends Controller
{
    public function index()
    {
        $id   = session('user')->id;
        $data = DB::table('shopcar')->where('uid', $id)->get();
        $sum = 0;
        foreach ($data as $k => $v) {
            $v->goodspic = DB::table('goods')->where('id', $v->goodsid)->first()->goodspic;
            $sum += ($v->price)*($v->number);
        }
        return view('home.shopcar.index')->with(['data' => $data,'sum'=>$sum]); 
    }

    public function shopcar(Request $request)
    {

        $data        = $request->except('_token');
        $data['uid'] = session('user')->id;
        $res         = DB::table('shopcar')->insert($data);
        return redirect("home/shopcar/index");
    }

    public function doEdit(Request $request)
    {
        $uid  = session('user')->id;
        $data = $request->only('id', 'number');
        $res  = DB::table('shopcar')->where('id', $data['id'])->update($data);
        if ($res) {
            $goods = DB::table('shopcar')->where('uid', $uid)->get();
            $sum   = 0;
            foreach ($goods as $key => $value) {
                $sum += ($value->price) * ($value->number);
            }
            $newnumber = DB::table('shopcar')->where('id', $data['id'])->first()->number;
            $data      = array(
                'sum'       => $sum,
                'newnumber' => $newnumber,
                );
            return $data;
        } else {
            $goods = DB::table('shopcar')->where('uid', $uid)->get();
            $sum   = 0;
            foreach ($goods as $key => $value) {
                $sum += ($value->price) * ($value->number);
            }
            $newnumber = DB::table('shopcar')->where('id', $data['id'])->first()->number;
            $data      = array(
                'sum'       => $sum,
                'newnumber' => $newnumber,
                );
        }
    }

    public function delete($id)
    {
        $res = DB::table('shopcar')->where('id', $id)->delete();
        if ($res) {
            return redirect('/home/shopcar/index');
        }
    }

    public function confirm()
    {
        $uid  = session('user')->id;
        $goods = DB::table('shopcar')->where('uid', $uid)->get();
        return redirect('/home/indent/confirm');
    }
}
